#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


int create_socket(void)
{

	int ret = 0;
	int sock = 0;
	struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));

	sock = socket(AF_INET,SOCK_STREAM,0);
	if(sock == -1)
	{
		perror("sock");
		exit(-1);
	}

	addr.sin_family = AF_INET;
    addr.sin_port = htons(6868);
    addr.sin_addr.s_addr = inet_addr("192.168.0.181");

	ret = bind(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind");
		exit(-1);
	}

	listen(sock,5);

	return sock;

}

int main()
{

	int fd1 = 0,fd2 = 0;
	int ret = 0;
	char dest[100] = {0};
	
	int sock = 0;

	sock = create_socket();

	fd1 = accept(sock,NULL,NULL);
	if(fd1 == -1)
	{
		perror("accpet");
		exit(-1);
	}
	fd2 = accept(sock,NULL,NULL);
	if(fd2 == -1)
	{
		perror("accpet");
		exit(-1);
	}

	fd_set rfds;

	FD_ZERO(&rfds);


	int max = fd1 > fd2?fd1:fd2;

	while(1)
	{
		FD_SET(fd1,&rfds);
		FD_SET(fd2,&rfds);

		ret = select(max + 1,&rfds,NULL,NULL,NULL);
		if(ret == -1)
		{
			perror("select");
			exit(-1);
		}

		if(FD_ISSET(fd1,&rfds))
		{
			ret  = recv(fd1,dest,99,0);
			if(ret == -1)
			{
				perror("recv");
			}else if(ret == 0)
			{
				close(fd1);

			}else
			{
				printf("dest is %s\n",dest);
			}

			FD_CLR(fd1,&rfds);
		}
		if(FD_ISSET(fd2,&rfds))
		{
			ret  = recv(fd2,dest,99,0);
			if(ret == -1)
			{
				exit(-1);
			}else if(ret == 0)
			{
				close(fd2);

			}else
			{
				printf("dest is %s\n",dest);
			}
			FD_CLR(fd2,&rfds);
		}
	}

	close(fd1);
	close(fd2);
	close(sock);

	return 0;

}










